package com.ttdc.interceptor;

import com.ttdc.pojo.User;
import com.ttdc.service.UserService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

//登录验证拦截
@Controller
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

	Logger log = Logger.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String basePath = request.getContextPath();
		String path = request.getRequestURI();
		if (!doLoginInterceptor(path, basePath)) {// 是否进行登陆拦截
			return true;
		}
		// 如果登录了，会把用户信息存进session
		log.info("---------------------开始进入请求地址拦截----------------------------");
		HttpSession session = request.getSession();
		List<User> users = (List<User>) session.getAttribute("userList");
		
		if (users == null) {
			response.sendRedirect(request.getContextPath() + "/signin");
		
		}

		if (users.get(0).getRoleId() == 3 || users.get(0).getRoleId() == 2) {
			if (doUserLoginInterceptor(path, basePath)) {
				return true;
			} else {
				log.info("沒有访问权限！");
				response.sendRedirect(request.getContextPath() + "/index");
			}
		} 
			return true;
		
	}
	/**
	 * 是否进行登陆过滤
	 * 
	 * @param path
	 * @param basePath
	 * @return
	 */
	private boolean doLoginInterceptor(String path, String basePath) {
		path = path.substring(basePath.length());
		Set<String> notLoginPaths = new HashSet<>();
		// 设置不进行登录拦截的路径：登录注册和验证码
		// notLoginPaths.add("/index");
		notLoginPaths.add("/re");
		// notLoginPaths.add("/dc");
		notLoginPaths.add("/signin");
		notLoginPaths.add("/login");
		notLoginPaths.add("/register");
		notLoginPaths.add("/kaptcha.jpg");
		notLoginPaths.add("/kaptcha");
		if (notLoginPaths.contains(path))
			return false;
		return true;
	}
	// vip用户
	private boolean doVipLoginInterceptor(String path, String basePath) {
		path = path.substring(basePath.length());
		Set<String> notLoginPaths = new HashSet<>();

		if (notLoginPaths.contains(path))
			return false;
		return true;
	}
	// 普通用户
	private boolean doUserLoginInterceptor(String path, String basePath) {
		path = path.substring(basePath.length());
		Set<String> notLoginPaths = new HashSet<>();
		notLoginPaths.add("/dc");
		notLoginPaths.add("/qtb_selectById");
		if (notLoginPaths.contains(path))
			return true;
		return false;
	}
}
